import Cookies from 'js-cookie'
export const setLocalStore = (name: string, content: string, session: boolean) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }

  session
    ? window.sessionStorage.setItem(name, content)
    : window.localStorage.setItem(name, content)
}

// 本地化获取
export const getLocalStore = (name: string, session: boolean) => {
  if (!name) return

  return session
    ? window.sessionStorage.getItem(name)
    : window.localStorage.getItem(name)
}

// 本地化删除
export const removeLocalStore = (name: string, session: boolean) => {
  if (!name) return
  return session
    ? window.sessionStorage.removeItem(name)
    : window.localStorage.removeItem(name)
}

// 语言设置
export function getLanguage(messages: object) {
  // 从cookis 里面取语言
  const chooseLanguage = Cookies.get('language')
  if (!chooseLanguage) {
    // 设置默认语言为中文
    Cookies.set('language', 'zh')
  }
  if (chooseLanguage) return chooseLanguage
  const language = navigator.language.toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale
    }
  }
  return 'en'
}
